import openpyxl
from common.logging_use import Logger
import os
from config import BASE_DIR
from config import loginExcelPath

'''excel表格从1开始计数'''


class ExcelUtil:
    logger = Logger.init_log_config('excel', os.path.join(BASE_DIR, 'log', 'excel.log'))

    def read_excel(self, path, sheet_name):
        try:
            wb = openpyxl.load_workbook(path)
            sheet = wb[sheet_name]
            '''获取行数和列数'''
            rows = sheet.max_row
            cols = sheet.max_column
            self.logger.debug("行数：%s，列数：%s" % (rows, cols))
            allData = []
            for i in range(2, rows + 1):
                row_data = []
                for j in range(1, cols + 1):
                    row_data.append(sheet.cell(row=i, column=j).value)
                self.logger.debug(f"第 {i} 行的数据: {row_data}")
                allData.append(row_data)
            self.logger.info(f"读取完成: {path}, sheet: {sheet_name}")
            return allData
        except FileNotFoundError as e:
            # 处理文件未找到的异常
            self.logger.error(f"文件未找到: {path}. Error: {e}")
            raise

        except KeyError as e:
            # 处理工作表不存在的异常
            self.logger.error(f"Sheet '{sheet_name}' 不能找到该工作表. Error: {e}")
            raise

        except Exception as e:
            # 处理其他未知异常
            self.logger.error(f"未知错误: {e}")
            raise


if __name__ == '__main__':
    excel = ExcelUtil()
    print(type(excel.read_excel(loginExcelPath, 'login')[0][1]))
